package com.ohs.bll.service.impl;

import java.util.List;
import java.util.Map;

import com.ohs.bll.service.RoomService;
import com.ohs.bll.util.Constant;
import com.ohs.dal.dao.AccountDAO;
import com.ohs.dal.dao.LocationDAO;
import com.ohs.dal.dao.RoomDAO;
import com.ohs.dal.dao.ScheduleDAO;
import com.ohs.dal.model.Account;
import com.ohs.dal.model.Location;
import com.ohs.dal.model.Room;
import com.ohs.dal.model.Schedule;
import com.ohs.dal.model.ScheduleId;

public class RoomServiceImpl implements RoomService {

	private RoomDAO roomDAO;
	private ScheduleDAO scheduleDAO;
	private LocationDAO locationDAO;
	private AccountDAO accountDAO;

	public void saveInTransaction(Room room, Map<Integer, Schedule> schedules, boolean updateStep, String username) {
		long roomId = roomDAO.saveOrUpdateAndReturn(room);
		for (int i=1; i <= schedules.size(); i++) {
			Schedule schedule = schedules.get(i);
			schedule.setId(new ScheduleId(roomId, i));
			scheduleDAO.update(schedule);
		}
		if (updateStep) {
			Account account = accountDAO.get(username);
			account.setStep(Constant.STEP_DONE_3);
			accountDAO.update(account);
		}
	}
	
	public void udpate(Room room) {
		roomDAO.update(room);
	}

	public Room get(long roomId) {
		return roomDAO.get(roomId);
	}

	public List<Room> list() {
		return roomDAO.list();
	}
	
	public List<Room> findByLocation(long locationId) {
		return roomDAO.findByLocaiton(locationId);
	}


	public RoomDAO getRoomDAO() {
		return roomDAO;
	}

	public void setRoomDAO(RoomDAO roomDAO) {
		this.roomDAO = roomDAO;
	}

	public boolean delete(Long roomId) {
		Room room = roomDAO.get(roomId);
		if (room != null) {
			List<Schedule> schedules = scheduleDAO.findByRoom(roomId);
			for(Schedule schedule : schedules) {
				scheduleDAO.delete(schedule);
			}
			this.roomDAO.delete(room);
			return true;
		}
		return false;
	}

	public ScheduleDAO getScheduleDAO() {
		return scheduleDAO;
	}

	public void setScheduleDAO(ScheduleDAO scheduleDAO) {
		this.scheduleDAO = scheduleDAO;
	}

	public List<Room> search(String keyword) {
		return roomDAO.search(keyword);
	}

	public boolean isSetupRoom(String username) {
		return roomDAO.isSetupRoom(username);
	}

	public List<Room> findByAccount(String username) {
		Location location = locationDAO.getByAccount(username);
		return roomDAO.findByLocaiton(location.getLocationId());
	}

	public LocationDAO getLocationDAO() {
		return locationDAO;
	}

	public void setLocationDAO(LocationDAO locationDAO) {
		this.locationDAO = locationDAO;
	}

	public AccountDAO getAccountDAO() {
		return accountDAO;
	}

	public void setAccountDAO(AccountDAO accountDAO) {
		this.accountDAO = accountDAO;
	}
	
	
}
